<template>
  <div class="cancel-requests-container">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>取消申请管理</h3>
          <el-button type="primary" @click="fetchRequests">刷新</el-button>
        </div>
      </template>

      <!-- 取消申请列表 -->
      <el-table :data="requestList" style="width: 100%" v-loading="loading">
        <!-- 基本信息列 -->
        <el-table-column prop="reservationId" label="预订编号" width="180" />
        <el-table-column prop="roomName" label="会议室" />
        <el-table-column label="预订时间" width="300">
          <template #default="{ row }">
            {{ formatDate(row.reservationDate) }} {{ formatTime(row.startTime) }} - {{ formatTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="申请人" />
        <el-table-column label="申请时间">
          <template #default="{ row }">
            {{ formatDateTime(row.requestTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <template v-if="row.status === 'pending'">
              <el-button 
                type="primary" 
                size="small"
                @click="handleApprove(row)"
              >
                同意
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="handleReject(row)"
              >
                拒绝
              </el-button>
            </template>
            <el-button
              size="small"
              @click="showDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="取消申请详情"
      width="600px"
    >
      <template v-if="selectedRequest">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预订编号">{{ selectedRequest.reservationId }}</el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusType(selectedRequest.status)">
              {{ getStatusText(selectedRequest.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="会议室">{{ selectedRequest.roomName }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ selectedRequest.userName }}</el-descriptions-item>
          <el-descriptions-item label="预订日期">{{ formatDate(selectedRequest.reservationDate) }}</el-descriptions-item>
          <el-descriptions-item label="使用时间">
            {{ formatTime(selectedRequest.startTime) }} - {{ formatTime(selectedRequest.endTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDateTime(selectedRequest.requestTime) }}</el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="selectedRequest.handleTime">
            {{ formatDateTime(selectedRequest.handleTime) }}
          </el-descriptions-item>

        </el-descriptions>
      </template>
    </el-dialog>

    <!-- 拒绝原因对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝取消申请"
      width="500px"
    >
      <div>
        <h1>确认拒绝取消申请</h1>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmReject"
            :loading="submitting"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getCancelRequests ,agreeCancelRequest,rejectCancelRequest } from '../../api/cancleOrderApi'

// 状态变量
const loading = ref(false)
const submitting = ref(false)
const detailDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const requestList = ref([])
const selectedRequest = ref(null)
const currentRequestId = ref(null)
const rejectForm = ref({
  reason: ''
})

// 获取取消申请列表
const fetchRequests = async () => {
  loading.value = true
  try {
    const response = await getCancelRequests()
    console.log(response);
    
    if (response.flag) {
      requestList.value = response.result
    } else {
      ElMessage.error(response.reason || '获取取消申请列表失败')
    }
  } catch (error) {
    console.error('获取取消申请列表失败:', error)
    ElMessage.error('获取取消申请列表失败')
  } finally {
    loading.value = false
  }
}

// 状态显示
const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    pending: '待处理',
    approved: '已同意',
    rejected: '已拒绝'
  }
  return map[status] || status
}

// 时间格式化
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}

const formatTime = (time) => {
  return time ? dayjs(time).format('HH:mm') : ''
}

const formatDateTime = (datetime) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm:ss') : ''
}

// 处理操作
const handleApprove = async (row) => {
  try {
    submitting.value = true
    const params = {
      requestId: row.requestId,
    }
    console.log();
    
    const response = await agreeCancelRequest(params)
    if (response.flag) {
      ElMessage.success('已同意取消申请')
      await fetchRequests()
    } else {
      ElMessage.error(response.reason || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

const handleReject = (row) => {
  selectedRequest.value = row
  currentRequestId.value = row.requestId
  rejectDialogVisible.value = true
}

const confirmReject = async () => {
  try {
    submitting.value = true
    const params = {
      requestId: currentRequestId.value,
    }
    console.log(params);
    
    const response = await rejectCancelRequest(params)
    if (response.flag) {
      ElMessage.success('已拒绝取消申请')
      rejectDialogVisible.value = false
      currentRequestId.value = null
      await fetchRequests()
    } else {
      ElMessage.error(response.reason || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

const showDetail = (row) => {
  selectedRequest.value = row
  detailDialogVisible.value = true
}

// 初始化
onMounted(() => {
  fetchRequests()
})
</script>

<style scoped>
.cancel-requests-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 